from tkinter import * 
from tkinter.scrolledtext import ScrolledText
import socket
import time


sock = None


#获取当前时间
def get_current_time():
    #current_time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
    current_time = time.strftime('%H:%M:%S | ',time.localtime(time.time()))
    return current_time


def func_connect():
    global sock

    host = txt_host.get()
    ip_port = host.split(':')
    ip = ip_port[0]
    port = int(ip_port[1])

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((ip, port))
    txt_recv.insert(1.0, get_current_time() + ip +':'+ip_port[1]+' 连接成功\n\n')
    return


def func_disconnect():
    global sock
    
    if sock:
        sock.close()
        sock = None
        txt_recv.insert(1.0, get_current_time() + '关闭连接\n\n')


def func_send():
    if not sock:
        func_connect()

    msg_send = txt_send.get(1.0, END)
    sock.send(msg_send.encode('utf-8'))
    txt_recv.insert(1.0, get_current_time() + 'send:\n' + msg_send + '\n')
    msg_recv = sock.recv(1024*64)
    txt_recv.insert(1.0, get_current_time() + 'recv:\n' + msg_recv.decode('utf-8') + '\n')
    return


root = Tk()
root.title('tcp text test tool')

txt_host = Entry(root, width=20)
txt_host.insert(0, '114.113.88.123:80')
bt_connect = Button(root, text='connect', width=10, command=func_connect)
bt_disconnect = Button(root, text='disconnect', width=12, command=func_disconnect)
txt_send = ScrolledText(root, width=70, height=50)
bt_send = Button(root, text='send', width=10, command=func_send)
txt_recv = ScrolledText(root, width=70, height=50)


txt_host.grid(row=0, column=0, padx=10, pady=10)
bt_connect.grid(row=0, column=1, padx=10, pady=10)
bt_disconnect.grid(row=0, column=2, padx=10, pady=10)
txt_send.grid(row=1, column=0, padx=10, pady=10)
bt_send.grid(row=1, column=1, padx=10, pady=10)
txt_recv.grid(row=1, column=2, padx=10, pady=10)


root.mainloop()